package org.example.listener;

import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = "mail")
public class MailQueueListener {
    @Resource
    JavaMailSender sender;
    @Value("${spring.mail.username}")
    String username;

    @RabbitHandler
    public void sendMailMessage(Map<String, Object> data) {
        String email = (String) data.get("email");
        Integer code = (Integer) data.get("code");
        String type = (String) data.get("type");
        SimpleMailMessage mailMessage = switch (type) {
            case "register" ->
                    createMessage("欢迎来到搞它搞它小程序", "您的邮件注册验证码为 " + code + "，有效时间为三分钟，为了保障您的安全，请勿向其他人泄露您的验证码", email);
            case "reset" ->
                    createMessage("这是您在搞它搞它小程序的密码重置邮件", "您好，您正在进行密码重置操作，验证码为 " + code + ",有效时间为三分钟，非本人操作，请无视", email);
            default -> null;
        };
        if (mailMessage == null) {
            return;
        }
        sender.send(mailMessage);
    }

    private SimpleMailMessage createMessage(String title, String content, String email) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(title);
        mailMessage.setText(content);
        mailMessage.setTo(email);
        mailMessage.setFrom(username);
        return mailMessage;
    }
}
